package hikari.utils;

import com.gooddies.wiring.annotations.Wire;
import com.gooddies.wiring.annotations.WiringComponent;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;

/**
 * @author Dmitry
 */
@WiringComponent(singleton = true, lazy = true)
public class FileContentReplacer {
    @Wire
    private Utils utils;
    private String readFileToString(String path) {
        try {
            return FileUtils.readFileToString(new File(path));
        } catch (IOException ex) {
            utils.logError(ex);
        }
        return null;
    }

    private void writeStringToFile(String path, String text) {
        try {
            FileUtils.writeStringToFile(new File(path), text);
        } catch (IOException ex) {
            utils.logError(ex);
        }
    }

    public void replaceTextInFile(String tagStart, String tagEnd, String filePath, String toBeReplaced) {
        String string = readFileToString(filePath);
        Matcher m = Pattern.compile("(<"+tagStart+">)(.*)(//<"+tagEnd+">)", Pattern.DOTALL).matcher(string);
        String filledBody = m.replaceAll(String.format("$1%s$3",toBeReplaced));
        writeStringToFile(filePath, filledBody);
    }
    
    public void replaceTextInFileWithoutComments(String tagStart, String tagEnd, String filePath, String toBeReplaced) {
        String string = readFileToString(filePath);
        Matcher m = Pattern.compile("(<"+tagStart+">)(.*)(<"+tagEnd+">)", Pattern.DOTALL).matcher(string);
        String filledBody = m.replaceAll(String.format("$1%s$3",toBeReplaced));
        writeStringToFile(filePath, filledBody);
    }
}
